package com.yuyou.tas.gateway.filter;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.yuyou.tas.gateway.bean.requestLog;
import com.yuyou.tas.util.bean.ReturnCode;
import com.yuyou.tas.util.bean.ReturnResult;
import com.yuyou.tas.util.tool.LogUtil;

public class TerminalLogFilter extends ZuulFilter {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static  List<String> exclusiveList=new ArrayList<String>();
	
	static {		
		exclusiveList.add("terminal");		
	}
	
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public Object run() {
		long traceId = Instant.now().toEpochMilli();
		requestLog log = new requestLog();
		log.setTraceId(traceId);
		try {
			RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletRequest request = ctx.getRequest();
			
			log.setUri(request.getRequestURI());
			log.setParams(request.getParameterMap());
			
			String body = StringUtils.EMPTY;
			InputStream stream = ctx.getResponseDataStream();
			body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
			log.setResp(body);
			ctx.set("isSuccess", true);
			if(StringUtils.isEmpty(body)){
				ReturnResult<String> res=new ReturnResult<String>(false,null,null,ReturnCode.code._3001.getCode(),ReturnCode.code._3001.getMessage());
				body=res.toJsonString();
			}		
			ctx.setResponseBody(body);// 返回错误内容
			ctx.getResponse().setContentType("text/html;charset=UTF-8");

		} catch (Exception e) {
			log.setResp(e.getMessage());
			LogUtil.error(logger, traceId+"网关日志错误:", e);
		}
		logger.info(JSONObject.toJSONString(log, false));
		return null;

	}

	@Override
	public boolean shouldFilter() {
		// 如果前一个过滤器的结果为true，则说明上一个过滤器成功了，需要进入当前的过滤，如果前一个过滤器的结果为false，则说明上一个过滤器没有成功，
		//则无需进行下面的过滤动作了，直接跳过后面的所有过滤器并返回结果  
		RequestContext ctx = RequestContext.getCurrentContext();  
		if(ctx.get("isSuccess")!=null && !(boolean) ctx.get("isSuccess")){
			return false;
		}		
		HttpServletRequest request = ctx.getRequest() ;
		String uri=request.getRequestURI();
		//登录绕过拦截器
		for(String exUri:exclusiveList){
			if(uri.contains(exUri)){
	            return true;
			}else{
				return false;
			}
		}
		return false;
	}

	@Override
	public int filterOrder() {
		return 1;
	}

	@Override
	public String filterType() {
		return "post";
	}

}
